import threading
import random
import time
# 生产者 消费者 Lock版本
g_money = 0
lock = threading.Lock()


class Producer(threading.Thread):
    def run(self):
        global lock
        global g_money
        for _ in range(10):
            lock.acquire()
            money = random.randint(1000, 10000)
            g_money += money
            print(threading.current_thread().name, "挣了{}元,当余额{}".format(money, g_money))
            time.sleep(1)
            lock.release()


class Customer(threading.Thread):
    def run(self):
        global g_money
        for _ in range(100):
            lock.acquire()
            money = random.randint(1000, 10000)
            if money <= g_money:
                g_money -= money
                print(threading.current_thread().name, "花了{}元,当前余额{}".format(money, g_money))
            else:
                print(threading.current_thread().name, "想花{}元,但余额不足,当前余额{}".format(money, g_money))
            time.sleep(1)
            lock.release()


def start():
    for i in range(5):
        th = Producer(name='生产者{}'.format(i))
        th.start()
    for i in range(5):
        cust = Customer(name='消费者{}'.format(i))
        cust.start()


if __name__ == '__main__':
    start()
